package de.tuhh.simsearch.model.persistence.usermgmt.eao;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.persistence.EntityManager;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.SAXException;

import de.tuhh.simsearch.junit.Utilities;
import de.tuhh.simsearch.model.persistence.contentmgmt.eao.ContentMgmtEAO;
import de.tuhh.simsearch.model.persistence.contentmgmt.entities.CategoryEntity;
import de.tuhh.simsearch.model.persistence.contentmgmt.entities.FileEntity;

public class ContentParserTest {

  private EntityManager em;
  private ContentMgmtEAO eao;

  @BeforeClass
  public static void onlyOnceAtStart() {

    EntityManager entityman = Utilities.getContentEntityManager();
    ContentMgmtEAO entityao = new ContentMgmtEAO(entityman);

    entityman.getTransaction().begin();

    String fn = "myFavoriteFile";
    String path = "/test/file";
    entityman.persist(new FileEntity(fn, path));

    Integer cId = 1;
    String cName = "history";
    entityman.persist(new CategoryEntity(cId, cName));

    entityman.getTransaction().commit();

  }

  @AfterClass
  public static void onlyOnceAtEnd() {

  }

  @Before
  public void setUp() throws Exception {

    em = Utilities.getContentEntityManager();
    eao = new ContentMgmtEAO(em);
  }

  @Test
public void testsetupFile() {
  
  ContentMgmtEAO cm = new ContentMgmtEAO();
  List<FileEntity> fe = cm.getAllFileEntitys();
  for (FileEntity f : fe) {
    File file = new File(f.getPath() + f.getFileName());
  
  }
}
  @Test
  public void testsetupParser(File file) throws IOException, SAXException, TikaException {

    InputStream is = new FileInputStream(file);
    Metadata metadata = new Metadata();
    BodyContentHandler ch = new BodyContentHandler();
    AutoDetectParser parser = new AutoDetectParser();

    String mimeType = new Tika().detect(file);
    metadata.set(Metadata.CONTENT_TYPE, mimeType);

    parser.parse(is, ch, metadata, new ParseContext());
    is.close();

    for (int i = 0; i < metadata.names().length; i++) {
      String item = metadata.names()[i];
      System.out.println(item + " -- " + metadata.get(item));
    }

    System.out.println(ch.toString());

  }

}
